import { removeToken } from '@/utils/storage';
import { getEnv } from '@tarojs/taro';
import { getRequest } from '@vh-mobile/pro-services';
import { eventsBus, toast, dialog, switchTab } from '@vh-mobile/pro-utils';
import { wxLogin } from '../global';
import { getCurrentInstance } from '@tarojs/taro';
export const {
  requestQuery,
  postBody,
  postQuery,
  getBody,
  getQuery,
  pathBody,
  pathQuery,
  postDownloadBlob,
  postDownload,
  postUploadFile,
  postFormDownloadBlob,
  postFormDownload,
} = getRequest({
  api_url: API_URL,
  sign_key: SIGN_KEY,
  version: VERSION,
  tokenStorage: 'TOKEN',
  responseConfig: {
    data: 'data',
    success: 0,
    code: 'code',
    message: 'msg',
  },
  httpError: (http: any) => {
    if (http.statusCode === 401) {
      removeToken();
      eventsBus.$trigger('GlobalEvents', {
        type: 'resetUserModel',
      });
      if (getEnv() === 'WEB') {
        window.location.replace(window.location.href);
      } else if (getEnv() === 'WEAPP') {
        let isHome: boolean = false;
        const router: any = getCurrentInstance().router;
        if (router.path === '/pages/index/index') {
          isHome = true;
        }
        dialog.alert('提示', '登录已失效', {
          confirmButtonText: isHome ? '立即登录' : '去首页',
          confirmButtonColor: 'red !important',
          asyncClose: true,
          beforeClose: () => {
            return new Promise((resolve) => {
              if (isHome) {
                wxLogin()
                  .then((res: any) => {
                    if (res.data && res.data.id) {
                      eventsBus.$trigger('GlobalEvents', {
                        type: 'login',
                        value: res.data,
                      });
                      resolve(true);
                    }
                  })
                  .catch(() => {});
              } else {
                switchTab({
                  url: '/pages/index/index',
                });
                resolve(true);
              }
            });
          },
        });
        return {
          errorMessageShow: false,
        };
      }
    } else if (http.statusCode === 404) {
      eventsBus.$pageTrigger('SetPageError', {
        status: 'NotFind',
      });
    }
    if (http.statusCode === undefined) {
      toast.fail('网络发生了意外!');
      // eventsBus.$pageTrigger('SetPageError', {
      //   status: 'NotNetwork',
      // });
      return { errorMessageShow: false };
    }
  },
});

// export const request = <T>(url: any, options: any, data?: T) => {
//   console.log(data);
//   requestQuery(url, options);
// };
